package com.zjj.learn.javaplus.pkg07.demo702;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 文件存储客户端，负责发送文件到服务端
 **/
public class UploadServer {

    private static String SERVER_FILE_PATH = "file\\server\\";

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9699);

        //循环建立连接
        while (true) {
            Socket socket = serverSocket.accept();

            new Thread(() -> {
                try {
                    //获取客户端发送的数据
                    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                    //创建输出流对象，将数据存储在服务端本地
                    FileOutputStream fos = new FileOutputStream(SERVER_FILE_PATH + System.currentTimeMillis() + ".png");
                    BufferedOutputStream bos = new BufferedOutputStream(fos);

                    //获取客户端的数据
                    byte[] b = new byte[1024];
                    int i;
                    while ((i = bis.read(b)) != -1) {
                        //将数据写入到服务端
                        bos.write(b, 0, i);
                        bos.flush();
                    }

                    bos.close();
                    //项客户端返回数据
                    OutputStream os = socket.getOutputStream();
                    os.write("文件发送成功".getBytes(StandardCharsets.UTF_8));
                    os.close();
                    System.out.println("数据接收成功");

                    //关闭资源
                    bis.close();
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }).start();

        }
    }
}
